﻿/*
* ========================================================================
* 类说明：
*   MES操作帮助类
* 
* 作者：HGS   时间：2024/11/4 13:29:54
* 
* 修改者：         时间：           
* 修改说明：
* ========================================================================
*/

using GZHJ.Tool;
using Nancy.Json;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using VM.Shared.Extensions;
using VM.Shared.ReturnValue;

namespace MESLib
{
    /// <summary>
    /// MES操作帮助类
    /// </summary>
    public class MesHelper
    {
        /// <summary>
        /// Post数据接口
        /// </summary>
        /// <param name="postUrl">接口地址</param>
        /// <param name="paramData">提交json数据</param>
        /// <param name="dataEncode">编码方式(Encoding.UTF8)</param>
        /// <returns></returns>
        private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string responseContent = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                webReq.Timeout = 2000;
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    //reqStream.Close();
                }
                using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode))
                    {
                        responseContent = sr.ReadToEnd().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return responseContent;
        }
        /// <summary>
        /// SN绑定蓝牙MAC
        /// </summary>
        /// <param name="SN"></param>
        /// <param name="Mac"></param>
        /// <param name="mesUrl"></param>
        /// <param name="factoryId"></param>
        /// <returns></returns>
        public static ReturnError SnBindMAC(string SN, string Mac, string mesUrl, string factoryId)
        {
            BindReturn list = new BindReturn();
            ReturnError mesReturn = new ReturnError();
            try
            {
                if (string.IsNullOrWhiteSpace(SN))
                {
                    mesReturn.ErrStr = $"SN不能为空！";
                    return mesReturn;
                }
                if (string.IsNullOrWhiteSpace(Mac))
                {
                    mesReturn.ErrStr = $"蓝牙Mac地址不能为空！";
                    return mesReturn;
                }
                //string url = mesUrl + "/jeecg-boot/iot/base/query";  //旧代码，注释到，这里后面的地址应该是错的，2024-08-22，HGS
                string url = mesUrl + "/jeecg-boot/iot/base/insert";
                //url = "http://172.16.43.200:8090/jeecg-boot/iot/base/insert";  //这句代码没啥用，注释掉，HGS
                BindMacData model = new BindMacData();
                model.type = "MAC_BIND";
                List<BindDetail> BindDetailList = new List<BindDetail>();
                BindDetail bindDetail = new BindDetail();
                bindDetail.sn = SN;
                bindDetail.bindList = new string[] { Mac };
                BindDetailList.Add(bindDetail);
                model.list = BindDetailList;
                string postdata = JsonConvert.SerializeObject(model);

                byte[] data = Encoding.UTF8.GetBytes((postdata));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 1000 * 10;
                string json = "";
                mesReturn.Request = postdata;
                //发送数据
                //json = Post(request, data);
                json = PostWebRequest(url, postdata, Encoding.UTF8);

                mesReturn.Response = json;

                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                list = js.Deserialize<BindReturn>(json);    //将json数据转化为对象类型并赋值给list
                if (list.code == 200)
                {
                    if (list.result.list.Count > 0 && list.result.list[0].sn.ToLower() == SN.ToLower()
                        && list.result.list[0].status.ToLower() == "y")
                    {
                        mesReturn.IsOK = true;
                    }
                    //mesReturn.ErrStr = list.result.list[0].message;
                }

                //将提示消息添加到返回参数中,2024-10-30
                if (list.result.list.Count > 0 && !string.IsNullOrWhiteSpace(list.result.list[0].message))
                {
                    mesReturn.ErrStr = list.result.list[0].message;
                }
                mesReturn.ErrCode = list.code;

                return mesReturn;
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }

        /// <summary>
        /// 验证当前产品标签是否正确
        /// </summary>
        /// <param name="SN"></param>
        /// <returns></returns>
        /// 
        public static ReturnError QuerySN(string SN, string deviceCode, string business, string mesUrl, string factoryId)
        {
            QueryReturn list = new QueryReturn();
            ReturnError mesReturn = new ReturnError();
            try
            {
                string url = mesUrl + "/jeecg-boot/iot/base/query";
                //url = "http://172.16.43.200:8090/jeecg-boot/iot/base/query";
                QueryModel model = new QueryModel();
                model.type = "ORDER_PRODUCT_SN";
                model.business = business;
                model.deviceCode = deviceCode;


                SN sN = new SN();
                sN.productSn = SN;
                List<SN> sList = new List<SN>();
                sList.Add(sN);

                model.list = sList;
                string postdata = JsonConvert.SerializeObject(model);

                byte[] data = Encoding.UTF8.GetBytes((postdata));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                if (request.Headers == null)
                {
                    request.Headers = new WebHeaderCollection();  //如果为空，增加判断，20240822，HGS
                }
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 1000 * 10;
                string json = "";
                mesReturn.Request = postdata;
                //发送数据
                //json = Post(request, data);
                json = PostWebRequest(url, postdata, Encoding.UTF8);

                mesReturn.Response = json;

                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                list = js.Deserialize<QueryReturn>(json);    //将json数据转化为对象类型并赋值给list
                if (list.code == 200)
                {
                    if (list.result.list.Count > 0 && list.result.list[0].sn.ToLower() == SN.ToLower() && list.result.list[0].status.ToLower() == "y")
                    {
                        mesReturn.IsOK = true;
                        //mesReturn.ErrStr = list.result.list[0].message;
                    }
                }
                //将提示消息添加到返回参数中,2024-10-30
                if (list.result.list.Count > 0 && !string.IsNullOrWhiteSpace(list.result.list[0].message))
                {
                    mesReturn.ErrStr = list.result.list[0].message;
                }
                mesReturn.ErrCode = list.code;

                return mesReturn;
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }

        /// <summary>
        /// 验证当前产品标签是否正确
        /// </summary>
        /// <param name="SN"></param>
        /// <returns></returns>
        public static ReturnError QuerySN(List<string> snList, string deviceCode, string business, string mesUrl, string factoryId)
        {
            QueryReturn list = new QueryReturn();
            ReturnError mesReturn = new ReturnError();
            try
            {
                string url = mesUrl + "/jeecg-boot/iot/base/query";
                //url = "http://172.16.43.200:8090/jeecg-boot/iot/base/query";
                QueryModel model = new QueryModel();
                model.type = "ORDER_PRODUCT_SN";
                model.business = business;
                model.deviceCode = deviceCode;


                List<SN> sList = new List<SN>();
                foreach (var sn in snList)
                {
                    sList.Add(new SN() { productSn = sn });
                }

                model.list = sList;
                string postdata = JsonConvert.SerializeObject(model);

                byte[] data = Encoding.UTF8.GetBytes((postdata));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                if (request.Headers == null)
                {
                    request.Headers = new WebHeaderCollection();  //如果为空，增加判断，20240822，HGS
                }
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 3000;
                string json = "";
                mesReturn.Request = postdata;
                //发送数据
                // json = Post(request, data);
                json = PostWebRequest(url, postdata, Encoding.UTF8);

                mesReturn.Response = json;

                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                list = js.Deserialize<QueryReturn>(json);    //将json数据转化为对象类型并赋值给list
                if (list.code == 200)
                {
                    if (list.result.list.Count > 1 &&
                        list.result.list[0].sn.ToLower() == snList[0].ToLower() &&
                        list.result.list[0].status.ToLower() == "y" &&
                        list.result.list[1].sn.ToLower() == snList[1].ToLower() &&
                        list.result.list[1].status.ToLower() == "y")
                    {
                        mesReturn.IsOK = true;
                        //mesReturn.ErrStr = $"{list.result.list[0].message}，{list.result.list[1].message}";
                    }
                }
                //将提示消息添加到返回参数中,2024-10-30
                if (list.result.list.Count > 0 && !string.IsNullOrWhiteSpace(list.result.list[0].message))
                {
                    mesReturn.ErrStr = list.result.list[0].message;
                }
                if (list.result.list.Count > 1 && !string.IsNullOrWhiteSpace(list.result.list[1].message))
                {
                    if (!string.IsNullOrWhiteSpace(mesReturn.ErrStr))
                    {
                        mesReturn.ErrStr += "，";
                    }
                    mesReturn.ErrStr += list.result.list[1].message;
                }
                mesReturn.ErrCode = list.code;

                return mesReturn;
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }

        /// <summary>
        /// 录入过站信息
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="ststus"></param>
        /// <param name="BadList"></param>
        /// <param name="business"></param>
        /// <param name="mesUrl"></param>
        /// <returns></returns>
        public static ReturnError Insert(string sn, string ststus, List<badcode> BadList, string business, string mesUrl, string factoryId, string deviceCode, string filePath)
        {

            InsertReturn insertReturn = new InsertReturn();
            ReturnError mesReturn = new ReturnError();
            try
            {
                string url = mesUrl + "/jeecg-boot/iot/base/insert";
                //url = "http://172.16.43.200:8090/jeecg-boot/iot/base/insert";
                InsertModel insertModel = new InsertModel();
                insertModel.type = "OVER_STATION";
                insertModel.business = business;
                detailed detailed = new detailed();
                List<detailed> detailedList = new List<detailed>();
                detailedList.Add(detailed);
                insertModel.list = detailedList;
                detailed.sn = sn;
                detailed.status = ststus;
                detailed.badList = BadList;
                detailed.imgPath = GetCustomFilePath(filePath);  //增加传递报告文件路径值,20240822,HGS

                insertModel.deviceCode = deviceCode;

                string postdata = JsonConvert.SerializeObject(insertModel);

                byte[] data = Encoding.UTF8.GetBytes((postdata));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                if (request.Headers == null)
                {
                    request.Headers = new WebHeaderCollection();  //如果为空，增加判断，20240822，HGS
                }
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 1000 * 10;
                string json = "";
                mesReturn.Request = postdata;
                //发送数据
                //json = Post(request, data);
                json = PostWebRequest(url, postdata, Encoding.UTF8);
                mesReturn.Response = json;

                //JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                //insertReturn = js.Deserialize<InsertReturn>(json);    //将json数据转化为对象类型并赋值给list   
                //mesReturn.ErrStr = insertReturn.message;
                //mesReturn.ErrCode = insertReturn.code;
                //mesReturn.IsOK = (insertReturn.code == 200);

                //修改为使用下面的方式，判断录入过站信息是否成功，2024-09-30
                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                insertReturn = js.Deserialize<InsertReturn>(json);    //将json数据转化为对象类型并赋值给list
                if (insertReturn.code == 200)
                {
                    if (insertReturn.result.list.Count > 0 && insertReturn.result.list[0].status.ToLower() == "y")
                    {
                        mesReturn.IsOK = true;
                    }
                    //mesReturn.ErrStr = insertReturn.result.list[0].message;
                }
                //将提示消息添加到返回参数中,2024-10-30
                if (insertReturn.result.list.Count > 0 && !string.IsNullOrWhiteSpace(insertReturn.result.list[0].message))
                {
                    mesReturn.ErrStr = insertReturn.result.list[0].message;
                }
                mesReturn.ErrCode = insertReturn.code;

                return mesReturn;
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }
        /// <summary>
        /// 录入过站信息
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="ststus"></param>
        /// <param name="BadList"></param>
        /// <param name="business"></param>
        /// <param name="mesUrl"></param>
        /// <returns></returns>
        public static ReturnError Insert(List<string> snList, string ststus, List<badcode> BadList, string business, string mesUrl, string factoryId, string deviceCode, string filePath)
        {

            InsertReturn insertReturn = new InsertReturn();
            ReturnError mesReturn = new ReturnError();
            try
            {
                string url = mesUrl + "/jeecg-boot/iot/base/insert";
                //url = "http://172.16.43.200:8090/jeecg-boot/iot/base/insert";
                InsertModel insertModel = new InsertModel();
                insertModel.type = "OVER_STATION";
                insertModel.business = business;
                List<detailed> detailedList = new List<detailed>();
                foreach (var sn in snList)
                {
                    detailed detailed = new detailed();
                    detailed.sn = sn;
                    detailed.status = ststus;
                    detailed.badList = BadList;
                    detailed.imgPath = GetCustomFilePath(filePath);  //增加传递报告文件路径值,20240822,HGS
                    detailedList.Add(detailed);
                }
                insertModel.list = detailedList;
                insertModel.deviceCode = deviceCode;

                string postdata = JsonConvert.SerializeObject(insertModel);

                byte[] data = Encoding.UTF8.GetBytes((postdata));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                if (request.Headers == null)
                {
                    request.Headers = new WebHeaderCollection();  //如果为空，增加判断，20240822，HGS
                }
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 1000 * 10;  //超时时间由原先的3秒更改为10秒
                string json = "";
                mesReturn.Request = postdata;
                //发送数据
                //json = Post(request, data);
                json = PostWebRequest(url, postdata, Encoding.UTF8);
                mesReturn.Response = json;

                //JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                //insertReturn = js.Deserialize<InsertReturn>(json);    //将json数据转化为对象类型并赋值给list   
                //mesReturn.ErrStr = insertReturn.message;
                //mesReturn.ErrCode = insertReturn.code;
                //mesReturn.IsOK = (insertReturn.code == 200);

                //修改为使用下面的方式，判断录入过站信息是否成功，2024-09-30
                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                insertReturn = js.Deserialize<InsertReturn>(json);    //将json数据转化为对象类型并赋值给list
                if (insertReturn.code == 200)
                {
                    if (insertReturn.result.list.Count > 0 && insertReturn.result.list[0].status.ToLower() == "y")
                    {
                        mesReturn.IsOK = true;
                    }
                    //mesReturn.ErrStr = insertReturn.result.list[0].message;
                }
                //将提示消息添加到返回参数中,2024-10-30
                if (insertReturn.result.list.Count > 0 && !string.IsNullOrWhiteSpace(insertReturn.result.list[0].message))
                {
                    mesReturn.ErrStr = insertReturn.result.list[0].message;
                }

                mesReturn.ErrCode = insertReturn.code;

                return mesReturn;
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }
        /// <summary>
        /// 上传采集测试项数据
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="factoryID"></param>
        /// <returns></returns>
        public static ReturnError InputCollectTestData(InputCollectTestDataRequest parameter, string factoryId, string mesUrl)
        {
            ReturnError mesReturn = new ReturnError();
            try
            {
                if (string.IsNullOrWhiteSpace(parameter.Business))
                {
                    mesReturn.ErrStr = $"上传采集测试项数据失败，当前工序编码不能为空！";
                    return mesReturn;
                }
                if (string.IsNullOrWhiteSpace(factoryId))
                {
                    mesReturn.ErrStr = $"上传采集测试项数据失败，工厂ID不能为空！";
                    return mesReturn;
                }
                if (string.IsNullOrWhiteSpace(parameter.SN))
                {
                    mesReturn.ErrStr = $"上传采集测试项数据失败，SN不能为空！";
                    return mesReturn;
                }

                string url = mesUrl.EndsWith("/") ? $"{mesUrl}jeecg-boot/iot/testdata/insert" : $"{mesUrl}/jeecg-boot/iot/testdata/insert";
                parameter.Type = "DEVICE_COLLECT_DATA";
                var jsonParam = Newtonsoft.Json.JsonConvert.SerializeObject(parameter);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                if (request.Headers == null)
                {
                    request.Headers = new WebHeaderCollection(); 
                }
                request.Headers.Add("factoryId", factoryId);
                request.Timeout = 1000 * 10;  //超时时间由原先的3秒更改为10秒
                string json = "";
                mesReturn.Request = jsonParam;
                json = PostWebRequest(url, jsonParam, Encoding.UTF8);
                mesReturn.Response = json;
                var response = JsonConvert.DeserializeObject<InputCollectTestDataResponse>(json, new JsonSerializerSettings
                {
                    Error = (s, e) => { e.ErrorContext.Handled = true; },
                    Converters = null,
                });
                if (null == response)
                {
                    mesReturn.ErrStr = $"上传采集测试项数据失败，Json实体转换失败，{json}";
                    return mesReturn;
                }

                if (response.Success && response.Code == 200)
                {
                    mesReturn.IsOK = true;
                    return mesReturn;
                }

                if (response != null && !string.IsNullOrEmpty(response.Message))
                {
                    mesReturn.ErrStr = response.Message;
                }
            }
            catch (Exception ex)
            {
                mesReturn.IsOK = false;
                mesReturn.ErrStr = ex.Message;
            }
            return mesReturn;
        }


        //================================= 辅助方法 ===================================
        /// <summary>
        /// 获取自定义文件路径
        /// </summary>
        /// <returns></returns>
        private static string GetCustomFilePath(string targetFilePath)
        {
            //MES供应商接口调用，要求传递的测试报告文件路径值变更：2024-08-26
            //原先格式：\172.16.43.200\sharefiles\测试线\成品测试设备1\3E\2024\08\24\7F3622CR8080117_Result_13-59-37_UUT_1.xlsx
            //要求格式：\测试线\成品测试设备1\3E\2024\08\24\7F3622CR8080117_Result_13-59-37_UUT_1.xlsx
            //处理方式：将前面两个层级的路径进行消除即可

            //string[] parts = targetFilePath.Split(System.IO.Path.DirectorySeparatorChar);
            if (string.IsNullOrWhiteSpace(targetFilePath))
            {
                return "";
            }
            string[] parts = targetFilePath.Split(new string[] { System.IO.Path.DirectorySeparatorChar.ToString() }, StringSplitOptions.RemoveEmptyEntries);
            int removeLength = 2;  //移除文件夹长度
            if (parts.Length > removeLength)
            {
                string newPath = "";
                for (int i = removeLength; i < parts.Length; i++)
                {
                    newPath = System.IO.Path.Combine(newPath, parts[i]);
                }
                return targetFilePath.StartsWith(System.IO.Path.DirectorySeparatorChar.ToString()) ? $"{System.IO.Path.DirectorySeparatorChar}{newPath}" : newPath;
            }

            return targetFilePath;
        }
    }
}
